<!-- 数据面板映射表-->
<template>
  <div>
    <div class="add-data-bar">
      <el-button icon="CirclePlus" size="small" @click="addData">添加</el-button>
    </div>
    <div class="table-wrap">
      <el-table
        :data="tableList"
        style="width: 100%"
        size="default"
        class="mapping-table"
        :tooltip-effect="xvueTheme"
      >
        <el-table-column
          prop="field"
          :label="$demoi18n('panelData.mapping.field')"
          min-width="100"
          :show-overflow-tooltip="true"
          :show-tooltip-when-overflow="true"
        >
          <template #default="{row,$index}">
            <span v-if="!row.isDelete" :title="row.field">
              {{ row.field }}
            </span>
            <VsFormItem
              v-else
              :prop="`tableData[${$index}].field`"
              :rules="
                generateRules({
                  required: false,
                })
              "
            >
              <el-input v-model="row.field" size="default" @change="changeField($event, row)"></el-input>
            </VsFormItem>
          </template>
        </el-table-column>
        <el-table-column :label="$demoi18n('panelData.mapping.mapping')" min-width="100" :render-header="renderTableHeader">
          <template #default="scope">
            <span v-if="!scope.row.skipVerification || scope.row.isVerification" class="mapping-scope">
              *
            </span>
            <VsFormItem
              :prop="`tableData[${scope.$index}].mapping`"
              :rules="
                generateExceptionRules({
                  required: !scope.row.skipVerification || !!scope.row.isVerification,
                  label: $demoi18n(scope.row.explain),
                })
              "
            >
              <!-- xTag 下拉项 -->
              <el-select
                v-if="form.dataSourceType === 'xTag'"
                v-model="scope.row.mapping"
                :class="`panel-data-select-${xvueTheme}`"
                :popper-class="`select-poper-${xvueTheme}`"
                filterable
                clearable
                placeholder
                size="default"
                @focus="setXtagMaxWidth"
                @visible-change="setTagTitle($event)"
                @change="xTagTableDataChange1(scope.row)"
              >
                <el-option
                  v-for="(item, index) in commonComp.mappingOptionsXTag"
                  :key="item.id"
                  class="panel-data-select-option"
                  :label="item.option_label"
                  :value="item.option_label"
                  :style="selectxTagStyle"
                >
                  <div v-if="item.type && item.type === 'add'" @click.stop="optionxTagClick(item, scope.row)">
                    <span class="select-option-slot-icon">
                      <el-button type="primary" class="select-icon" link>
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </el-button>
                    </span>
                    <span class="select-option-slot-text" :style="{ width: `${xTagTextWidth}px` }">
                      &nbsp;{{ item.option_label }}
                    </span>
                  </div>
                  <div v-else-if="item.type && item.type === 'edit'">
                    <span class="select-option-slot-icon select-option-slot-icon-edit">
                      <el-button
                        type="primary"
                        class="select-icon"
                        :title="$demoi18n('btn.edit')"
                        link
                        @click.stop="optionxTagClick(item, scope.row)"
                      >
                        <el-icon>
                          <EditPen />
                        </el-icon>
                      </el-button>
                      <el-button
                        type="primary"
                        class="select-icon"
                        :title="$demoi18n('btn.delete')"
                        link
                        @click.stop="optionxTagDelete(index)"
                      >
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </el-button>
                    </span>
                    <span class="select-option-slot-text" :style="{ width: `${xTagTextWidth}px` }">
                      {{ item.option_label }}
                    </span>
                  </div>
                  <div v-else>
                    <span>{{ item.option_label }}</span>
                  </div>
                </el-option>
              </el-select>

              <!-- xMiner 下拉项 -->
              <el-select
                v-else
                v-model="scope.row.mapping"
                :class="`panel-data-select-${xvueTheme}`"
                :popper-class="`select-poper-${xvueTheme}`"
                filterable
                clearable
                placeholder
                size="default"
                @focus="setMaxWidth"
                @visible-change="setTagTitle($event)"
                @change="xMinerTableDataChange1(scope.row)"
              >
                <el-option
                  v-for="item in commonComp.mappingOptions"
                  :key="item.id"
                  class="panel-data-select-option"
                  :label="item.option_label"
                  :value="item.option_value"
                  :style="selectStyle"
                >
                  <div class="vs_ellipsis" :title="`${item.option_label} (${item.option_value})`">{{
                    item.option_label
                  }}</div>
                </el-option>
              </el-select>
            </VsFormItem>
          </template>
        </el-table-column>
        <el-table-column width="20">
          <template #default="{row}">
            <span class="delete-icon">
              <el-icon v-if="row.isDelete" style="cursor:pointer;color:#39f" @click="deleteRow(row)">
                <Delete />
              </el-icon>
            </span>
          </template>
        </el-table-column>

        <el-table-column
          prop="explain"
          :label="$demoi18n('panel.th.explain')"
          min-width="36"
          :render-header="renderTableHeader"
          :show-overflow-tooltip="true"
          :show-tooltip-when-overflow="true"
        >
          <template #default="scope">
            <span>{{ $demoi18n(scope.row.explain) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script lang="jsx">
import xTagBase from '@/components/panel-data/xtag-base.js';
import VsFormItem from '@/components/common/vs-form-item/vs-form-item.vue';
import { cloneDeep } from 'lodash';

export default {
  name: 'PanelDataTable',
  components: {
    VsFormItem,
  },
  mixins: [xTagBase],
  props: {
    form: {
      type: Object,
      default() {
        return {
          tableData: [],
        };
      },
    },
    chartType: {
      type: String,
      default: '',
    },
    config: Object,
    commonComp: Object,
  },
  emits: ['update-tabledata'],
  data() {
    return {
      tableList: cloneDeep(this.form.tableData),
      addTemplates: {
        x: 0,
        y: 0,
        z: 0,
      },
      fieldIdList: ['x', 'y', 'z'],
    };
  },
  watch: {
    'form.tableData': {
      handler(newVal) {
        this.tableList = cloneDeep(this.form.tableData);
      }, deep: true,
    },
  },
  methods: {
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
    emitTableList() {
      this.$emit('update-tabledata', this.tableList);
    },
    addData() {
      let item = {};
      if (this.chartType === 'bubble') {
        const lastFieldId = this.tableList[this.tableList.length - 1]?.fieldId;
        let itemPre = 'x';
        if (lastFieldId) {
          itemPre = lastFieldId.slice(0, 1);
        }
        const index = this.addTemplates[itemPre] + 1;
        item = {
          isDelete: true,
          field: `${itemPre}${index}`,
          fieldId: `${itemPre}${index}`,
          mapping: `${itemPre}${index}`,
          explain: '信息文本编辑所需要的变量',
        };
        this.addTemplates[itemPre] = index;
      } else {
        const reg = 'desc';
        const descIndex = this.tableList.map(({ fieldId })=>new RegExp(reg, 'g').test(fieldId) ? fieldId.replace('desc', '') : null).filter(id=>id);
        const maxtIndex = descIndex.length ? Math.max(...descIndex) : 0;
        item = {
          isDelete: true,
          field: `desc${maxtIndex + 1}`,
          fieldId: `desc${maxtIndex + 1}`,
          mapping: `desc${maxtIndex + 1}`,
          explain: '描述信息文本编辑所需要的变量',
        };
      }
      this.tableList.push(item);
      this.emitTableList();
    },
    deleteRow(row) {
      this.tableList = this.tableList.filter(({ field })=>field !== row.field);
      this.emitTableList();
    },
    changeField(val, row) {
      if (this.chartType === 'bubble') {
        const { field } = row;
        const curFieldId = field.slice(0, 1);
        const fieldIdIndex = Number(field.substring(1));
        if (this.fieldIdList.includes(curFieldId) && !isNaN(fieldIdIndex)) {
          const index = Math.max(this.addTemplates[curFieldId], fieldIdIndex);
          this.addTemplates[curFieldId] = index;
          row.fieldId = `${curFieldId}${index}`;
        }
      } else {
        this.tableList = this.tableList.map(item=>{
          const { fieldId } = item;
          if (fieldId && fieldId === row.fieldId) {
            return {
              ...item,
              field: val,
            };
          }
          return { ...item };
        });
      }
      this.emitTableList();
    },
    xMinerTableDataChange1(row) {
      this.xMinerTableDataChange(row);
      this.emitTableList();
    },
    xTagTableDataChange1(row) {
      this.xTagTableDataChange(row);
      this.emitTableList();
    },
  },
};
</script>
